<template>
  <el-form :model="model" ref="formRef" v-bind="$attrs">
    <el-row :gutter="10">
      <el-col v-for="item in schema" :key="item.key" :span="item.span">
        <el-form-item :label="item.label" :prop="item.model">
          <!-- input -->
          <template v-if="item.component==='input'">
            <el-input v-model="model[item.model]" v-bind="item.props||{}"></el-input>
          </template>
          <!-- select -->
          <template v-if="item.component==='select'">
            <el-select v-model="model[item.model]" v-bind="item.props||{}">
            <el-option v-for="option in item.selectOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value">
              </el-option>
            </el-select>
          </template>
          <!-- button -->
          <template v-if="item.component==='submit-button'">
            <el-button v-bind="item.props||{}" @click="submit(item.handleSubmit)">{{ item.btnText }}</el-button>
          </template>

          <template v-if="item.component==='button'">
            <el-button v-bind="item.props||{}" v-on="item.listeners">{{ item.btnText }}</el-button>
          </template>

        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  
</template>

<script lang="ts">
export default {
  name: 'XForm',
}
</script>

<script lang="ts" setup>
  import type { FormInstance } from 'element-plus'
  import { ref } from 'vue'

  const props = defineProps<{
    schema: any[],
    model: any
  }>()

  const formRef = ref<FormInstance>()
  const submit = async (cb: (values: any) => void) => {
    // 表单校验
    await formRef.value?.validate()
    // 通过后调用cb
    cb(props.model)
  }
</script>

<style scoped>

</style>
